package cn.ug.info.service.impl;

import cn.ug.core.ensure.Ensure;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import cn.ug.aop.RemoveCache;
import cn.ug.aop.SaveCache;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.status.DeleteStatus;
import cn.ug.info.bean.ArticleBean;
import cn.ug.info.mapper.ArticleMapper;
import cn.ug.info.mapper.entity.Article;
import cn.ug.info.service.ArticleService;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static cn.ug.config.CacheType.OBJECT;
import static cn.ug.config.CacheType.SEARCH;

/**
 * @author kaiwotech
 */
@Service
public class ArticleServiceImpl extends BaseServiceImpl implements ArticleService {
	
	@Resource
	private ArticleMapper articleMapper;

	@Resource
	private DozerBeanMapper dozerBeanMapper;

	@Override
	@RemoveCache(cleanSearch = true)
	public int save(ArticleBean entityBean) {
		// 数据完整性校验
		if(null == entityBean || StringUtils.isBlank(entityBean.getTitle())) {
			Ensure.that(true).isTrue("11000401");
		}
		if(exists(entityBean, entityBean.getId())){
            // 该数据已存在
        	Ensure.that(true).isTrue("00000004");
        }
		Article entity = dozerBeanMapper.map(entityBean, Article.class);
		if(StringUtils.isBlank(entity.getId())) {
			entity.setId(UF.getRandomUUID());
			if(StringUtils.isNotBlank(entityBean.getStopTimeString())){
				entity.setStopTime(UF.getDate(entityBean.getStopTimeString()));
			}
            if(StringUtils.isNotBlank(entityBean.getStartTimeString())){
                entity.setStartTime(UF.getDate(entityBean.getStartTimeString()));
            }
		}
		articleMapper.insert(entity);

        return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int update(String id, ArticleBean entityBean) {
        // 数据完整性校验
		if(null == entityBean || StringUtils.isBlank(entityBean.getId()) || StringUtils.isBlank(entityBean.getTitle())) {
			Ensure.that(true).isTrue("11000401");
		}
		if(exists(entityBean, entityBean.getId())){
			// 该数据已存在
			Ensure.that(true).isTrue("00000004");
		}
		Article entity = articleMapper.findById(entityBean.getId());
		if(StringUtils.isNotBlank(entityBean.getStopTimeString())){
			entity.setStopTime(UF.getDate(entityBean.getStopTimeString()));
		}
        if(StringUtils.isNotBlank(entityBean.getStartTimeString())){
            entity.setStartTime(UF.getDate(entityBean.getStartTimeString()));
        }
		dozerBeanMapper.map(entityBean, entity);

		articleMapper.update(entity);
		return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int delete(String id) {
		if(StringUtils.isBlank(id)) {
			return 0;
		}

		return articleMapper.delete(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int deleteByIds(String[] id){
		if(id == null || id.length<=0){
			return 0;
		}

		return articleMapper.deleteByIds(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int removeByIds(String[] id) {
		if(id == null || id.length<=0){
			return 0;
		}

		return articleMapper.updateByPrimaryKeySelective(
				getParams()
						.put("id", id)
						.put("deleted", DeleteStatus.YES)
						.toMap()
		);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public boolean exists(ArticleBean entityBean, String id) {
		if(null == entityBean || StringUtils.isBlank(entityBean.getTitle())) {
			return false;
		}

		int rows = articleMapper.exists(
				getParams()
						.put("title", entityBean.getTitle())
						.put("articleClassId", entityBean.getArticleClassId())
						.put("id", id)
						.toMap()
		);
		return rows > 0;
	}

	@Override
	@SaveCache(cacheType = OBJECT)
	public ArticleBean findById(String id) {
		if(StringUtils.isBlank(id)) {
			return null;
		}

		Article entity = articleMapper.findById(id);
		if(null == entity) {
			return null;
		}

		ArticleBean entityBean = dozerBeanMapper.map(entity, ArticleBean.class);
		if(entity.getStopTime() != null) entityBean.setStopTimeString(UF.getFormatDateTime(entity.getStopTime()));
		entityBean.setAddTimeString(UF.getFormatDateTime(entity.getAddTime()));
		entityBean.setModifyTimeString(UF.getFormatDateTime(entity.getModifyTime()));
        entityBean.setStartTimeString(UF.getFormatDateTime(entity.getStartTime()));
        entityBean.setChannelIds(entity.getChannelIds());
		return entityBean;
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<ArticleBean> findList(String order, String sort, String articleClassId, Integer status, String keyword, String startTime, String endTime){
		return query(order, sort, articleClassId, status, keyword, startTime, endTime);
	}

	@Override
	/*@SaveCache(cacheType = SEARCH)*/
	public DataTable<ArticleBean> query(String order, String sort, int pageNum, int pageSize, String articleClassId, Integer status, String keyword, String startTime, String endTime){
		Page<ArticleBean> page = PageHelper.startPage(pageNum, pageSize);
		List<ArticleBean> list = query(order, sort, articleClassId, status, keyword, startTime, endTime);
		return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), list);
	}

	@Override
	public boolean articleJob() {
		//获取设置时间
		List<ArticleBean> list = findList(null,null,"hot_activity",null,null,null,null);
		if(list != null && !list.isEmpty()){
			for(ArticleBean article:list){
				LocalDateTime stopTime = LocalDateTime.parse(article.getStopTimeString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
				LocalDateTime currentTime = LocalDateTime.now();
				//设置活动关闭
				if(currentTime.compareTo(stopTime) >=0){
					//更新状态
					articleMapper.updateArticleStop(article.getId());
				}
			}
		}
		return false;
	}

	@Override
	public int read(String id) {
		return articleMapper.addReadNum(id);
	}

	/**
	 * 获取数据列表
	 * @param order				排序字段
	 * @param sort				排序方式 desc或asc
	 * @param articleClassId	分类ID
	 * @param status			状态
	 * @param keyword			关键字
	 * @return					列表
	 */
	private List<ArticleBean> query(String order, String sort, String articleClassId, Integer status, String keyword, String startTime, String endTime){
		List<ArticleBean> dataList = new ArrayList<>();
		List<Article> list = articleMapper.query(
				getParams(keyword, order, sort)
						.put("articleClassId", articleClassId)
						.put("status", status)
						.put("startTime", startTime)
						.put("endTime", endTime)
						.toMap());
		for (Article o : list) {
			ArticleBean objBean = dozerBeanMapper.map(o, ArticleBean.class);
			objBean.setAddTimeString(UF.getFormatDateTime(o.getAddTime()));
			objBean.setModifyTimeString(UF.getFormatDateTime(o.getModifyTime()));
			objBean.setStartTimeString(UF.getFormatDateTime(o.getStartTime()));
			if("hot_activity".equals(articleClassId)){
				objBean.setStopTimeString(UF.getFormatDateTime(o.getStopTime()));
				LocalDateTime currentTime = LocalDateTime.now();
				if(currentTime.compareTo(o.getStopTime()) > 0){
					objBean.setIsStop(2);
				}else{
					objBean.setIsStop(1);
				}
			}
			objBean.setHits(objBean.getHits()==null?10000:objBean.getHits()+10000);
			dataList.add(objBean);
		}
		return dataList;
	}


	@Override
	public Article getByArticleClassIdAndTitle(String articleClassId, String title) {

		return activityTime(articleClassId,title,null);
	}

	@Override
	public Article activityTime(String articleClassId, String title, String date) {
		Article bean = articleMapper.activityTime(articleClassId,title,null);
		return bean;
	}

	@Override
	public boolean canApply(String memberId, String startTime, String stopTime) {
		int count = articleMapper.canApply(memberId,startTime,stopTime);
		if (count <1){
			return false;
		}
		return true;
	}
}

